(function($){

$.fn.sweetPages = function(opts){

	if(!opts) opts = {};
	
	var resultsPerPage = opts.perPage || 3;
    var colsCount = opts.cols || 4;
    var rowHeigth = opts.rowHeight || 250;

    function randomFadeInItems() {
        $('.gallery_item').each(function(index, element) {
            var sleepTime = Math.floor(Math.random() * 1000);
            var t = setTimeout(function() {
                $(element).fadeTo(400, 0.99);
            }, sleepTime);
        });
    }

    function hideItems() {
        $('.gallery_item').each(function(index, element) {
            $(element).fadeTo(0, 0);
        });
    }

    function initRandomFadeIn() {
        hideItems();
        setTimeout(randomFadeInItems, 150);
    }

    initRandomFadeIn();

	var ul = this;
	var li = ul.find('li');
	var elemCount = li.size();
    var rowsHeigthTotal = 0;
    if (elemCount > resultsPerPage) {
        var rowsCount = resultsPerPage / colsCount;
        rowsHeigthTotal = rowsCount*rowHeigth;
    } else {
        rowsHeigthTotal = Math.ceil(elemCount / colsCount) * rowHeigth;
    }


	li.each(function(){
		var el = $(this);
		el.data('height',el.outerHeight(true));
	});

	var pagesNumber = Math.ceil(li.length/resultsPerPage);

	if(pagesNumber<2) {

        ul.height(rowsHeigthTotal);
        return this;
    }

	var swControls = $('<div class="swControls">');
	
	for(var i=0;i<pagesNumber;i++)
	{
		li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="swPage" />');
		swControls.append('<a href="" class="swShowPage">'+(i+1)+'</a>');
	}

	ul.append(swControls);
	
	var maxHeight = 0;
	var totalWidth = 0;
	
	var swPage = ul.find('.swPage');
	swPage.each(function(){
		var elem = $(this);
		totalWidth+=elem.outerWidth();
		elem.css('float','left').width(ul.width());
	});
	
	swPage.wrapAll('<div class="swSlider" />');
	ul.height(rowsHeigthTotal);
	
	var swSlider = ul.find('.swSlider');
	swSlider.append('<div class="clear" />').width(totalWidth);

	var hyperLinks = ul.find('a.swShowPage');
	
	hyperLinks.click(function(e){
        $('.gallery_item').hide();
		$(this).addClass('active').siblings().removeClass('active');
		swSlider.stop().animate({'margin-left':-(parseInt($(this).text())-1)*ul.width()},'fast', function(){
            initRandomFadeIn();
        });
		e.preventDefault();
	});

	hyperLinks.eq(0).addClass('active');

	swControls.css({
		'left':'50%',
		'margin-left':-swControls.width()/2
	});
	
	return this;
	
}})(jQuery);